package cn.zane.chatgpt.data.domain.auth.service;

import cn.zane.chatgpt.data.domain.auth.model.entity.AuthStateEntity;
import cn.zane.chatgpt.data.domain.auth.model.valobj.AuthTypeVO;
import com.google.common.cache.Cache;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @author: zane
 * @date: 2025-09-19
 * @description: 鉴权服务
 */
@Slf4j
@Service
public class AuthService extends AbstractAuthService {

    @Resource
    private Cache<String, String> codeCache;

    @Override
    public AuthStateEntity checkCode(String code) {
        // 获取验证码校验
        String openId = codeCache.getIfPresent(code);
        if (StringUtils.isBlank(openId)) {
            log.info("鉴权，用户收到的验证码不存在 {}", code);
            return AuthStateEntity.builder()
                    .code(AuthTypeVO.A0001.getCode())
                    .info(AuthTypeVO.A0001.getInfo())
                    .build();
        }
        // 删除缓存的Key值
        codeCache.invalidate(openId);
        codeCache.invalidate(code);

        // 验证码校验成功
        return AuthStateEntity.builder()
                .code(AuthTypeVO.A0000.getCode())
                .info(AuthTypeVO.A0000.getInfo())
                .openId(openId)
                .build();
    }

    @Override
    public String generateAccessCode(HttpServletRequest request) throws NoSuchAlgorithmException {
        // 使用 IP + User-Agent 来区分设备
        String raw = request.getRemoteAddr()
                + request.getHeader("User-Agent");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8));

        return "";
    }

    @Override
    public String openid(String token) {
        return "";
    }
}
